package zheezes.protocol.impl.gbw.format;

import java.math.BigDecimal;
import java.util.Arrays;

import zheezes.util.ArrayUtil;
import zheezes.util.format.NumberFormat;


public class DataForm09 extends DataForm {
public static final int SIZE = 3;
	
	private BigDecimal value;
	private int symbol;
	
	@Override
	public int sizeof() {
		return SIZE;
	}

	@Override
	public int getBytes(byte[] buf, int offset) {
		int idx = offset;
		if(value != null) {
			buf[idx++] = NumberFormat.getByte(value, NumberFormat.DIMI);
			buf[idx++] = NumberFormat.getByte(value, NumberFormat.MICRO);
			buf[idx] = NumberFormat.getByte(value, NumberFormat.UNIT);
			switch (symbol) {
			case 0:
				buf[idx] &= 0x7F;
				break;
			case 1:
				buf[idx] |= 0x80;
				break;
			}
			idx++;
		} else {
			Arrays.fill(buf, idx, idx + 2, (byte) 0xEE);
			idx += 2;
		}
		return idx - offset;
	}

	@Override
	public int setBytes(byte[] buf, int offset) {
		int idx = offset;
		if (ArrayUtil.count(buf, idx, (byte) 0xEE) < 2) {
			value = new BigDecimal("0.0");
			value = NumberFormat.setByte(value, NumberFormat.DIMI, buf[idx++]);
			value = NumberFormat.setByte(value, NumberFormat.MICRO, buf[idx++]);
			value = NumberFormat.setByte(value, NumberFormat.UNIT, buf[idx]);
			symbol = (buf[idx] >> 7) & 0x01;
			idx++;
		} else {
			value = null;
			symbol = -1;
			idx += 2;
		}
		
		return idx - offset;
	}

	public BigDecimal getValue() {
		return value;
	}

	public void setValue(BigDecimal value) {
		this.value = value;
	}

	public int getSymbol() {
		return symbol;
	}

	public void setSymbol(int symbol) {
		this.symbol = symbol;
	}
}
